package com.jsj.subway.ai.demo.dto;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.jsj.subway.ai.common.Role;
import com.jsj.subway.ai.largemodel.models.Message;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.validation.constraints.NotNull;
import java.util.*;

@Slf4j
public class ChatDTO {


    @Data
    //@ApiModel
    public static class MessageRequest{
        //@ApiModelProperty("会话ID")
        Long sessionId;
        //@ApiModelProperty("会话类型 1文本 2 图文 3 语音")
        Integer type;
        //@ApiModelProperty("会话内容 如果是文本就是字符串 如果是图文 就是数组 对象")
        /**
         *  [{text:""}]
         */
        @NotNull
        Object content;
        //@ApiModelProperty("是否需要显示文件 0-否 1-是 则将最近的一个文件名展示出来")
        Integer hasFile;
        //1-首次 剩余是其他
        Integer isFirst;
    }

    @Data
    //@ApiModel
    public static class UpdateTitleReq{
            String title;
    }

    @Data
    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class MessageRecord {
        //@ApiModelProperty("recordId")
        String recordId;
        //@ApiModelProperty("角色")
        String role;
        //@ApiModelProperty("1 文本 2图文 3 语音")
        int type;
        //@ApiModelProperty("回复内容")
        Object content;
        //@ApiModelProperty("关联关键词 猜你想搜")
        List<String> related_keywords;
        //@ApiModelProperty("参考来源")
        Object nodes;
        //@ApiModelProperty("推荐问题")
        Object related_queries;
        @JsonIgnore
        private List<Message> messages;

        String time;



        public Message toApiObject() {
            Message c = new Message();
            c.setContent(this.content);
            c.setRole(this.role);
            return c;
        }
    }

    public  static MessageRecord toMessageRecord(List<Message> messages,Boolean stream){
        if(CollectionUtil.isEmpty(messages)){
            return new MessageRecord();
        }
        Message s = new Message();
        if(stream){
            s = messages.stream().filter((x)->{
                return  Objects.isNull(x.getRole()) || Role.ASSISTANT.getLabel().equals(x.getRole());
            }).findFirst().orElse(null);
        }else {
            s = messages.stream().filter((x)->{
                return  Role.ASSISTANT.getLabel().equals(x.getRole());
            }).findFirst().orElse(null);
        }

        if (s==null){
            s = messages.get(0);
        }
        MessageRecord  c = new MessageRecord();
        if (s.getContent() instanceof  List){
            ((List<?>) s.getContent()).forEach((a)->{
                if (a instanceof Map &&  ((Map) a).containsKey("image")){
                    String imageBase64 = ((Map) a).get("image").toString();
                    if (imageBase64.indexOf("base64,")==-1){
                        int index = imageBase64.indexOf(";");
                        StringBuilder st = new StringBuilder(imageBase64);
                        ((Map) a).put("image",st.insert(index+1,"base64,").toString());
                    }
                }
                if (a instanceof Map &&  ((Map) a).containsKey("fileView")){
                    ((Map) a).put("type","file");
                }
            });
        }

        if (s.getContent() instanceof  Map){
            if (((Map) s.getContent()).containsKey("fileView")){
                ((Map) s.getContent()).put("type","file");
            }
        }
        c.setContent(s.getContent());
        c.setRole(s.getRole());
        c.setMessages(messages);
        if (s.getContent() instanceof Collection){
            c.setType(2);
        }else{
            c.setType(1);
        }
        c.setTime(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        return c;
    }

    public static MessageRecord toMessage(int type,String content,String originMessages){
        ObjectMapper mapper = new ObjectMapper();
        try {
            MessageRecord res = mapper.readValue(content, MessageRecord.class);
            if (StrUtil.isNotEmpty(originMessages)){
                if(checkJsonIsArray(originMessages)){
                    List<Message> messages = mapper.readValue(originMessages, new TypeReference<List<Message>>() {});
                    res.setMessages(messages);
                }else {
                    Message message = mapper.readValue(originMessages, Message.class);
                    res.setMessages(Collections.singletonList(message));
                }
            }
            res.setType(type);
            return res;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return new MessageRecord();
    }



    public static Boolean checkJsonIsArray(String json) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode jsonNode = objectMapper.readTree(json);
            if (jsonNode.isObject()) {
              return false;
            } else if (jsonNode.isArray()) {
                return true;
            } else {
                log.error("当前json字符串非法");
               return false;
            }
        } catch (Exception e) {
            log.error("checkJsonIsArray is error :{}",e.getMessage());
        }
        return false;
    }
}
